package com.ciwong.ciwongwrite;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.ciwongwrite.ui.CWBaseActivity;
import com.ciwong.ciwongwrite.widget.CWPallete;
import com.ciwong.ciwongwrite.widget.CWPanel;
import com.ciwong.ciwongwrite.widget.CWToast;
import com.ciwong.ciwongwrite.widget.Circle;
import com.ciwong.ciwongwrite.widget.Square;
import com.ciwong.mobilelib.utils.BaseSystem;


public class JournalActivity extends CWBaseActivity implements
        OnClickListener {
    private static final int PAINT_STYLE_SELECT = 0;

    private static final int PAINT_STYLE_NORMAL = 1;

    private static final int REQUEST_CODE_LOGIN = 1;

    private static final int REQUEST_CODE_PERMISSION_SET = 2;

    private static final int REQUEST_CODE_CAPTURE = 3;

    private static final int REQUEST_CODE_MEDIA = 4;

    private static final int REQUEST_CODE_PERMISSION_MODIFY = 5;
    public static final String PHOTOPATH = "PHOTOPATH";

    private static int POPU_PAINT_STYLE_WIDTH;

    private RadioButton iv_paintStyle, iv_eraser;

    private ImageView iv_exit;

    public TextView tv_finish;
    @Override
    protected void onStart() {

        super.onStart();
    }

    private ViewGroup mainContainer;

    private PopupWindow mPaintStyle;

    private CWPanel panel;
    private CWPallete mPallete;


    public static boolean isWrite = false;

    public static Map<String, Object> maps;

    public static List<Map> oldlist = new ArrayList<Map>(); //这是数据库存在的


    public static String tempPath = "";// 保存临时的地址

    public int sumpage = 0; //总页数

    public String tempsclass = "";

    public int tempsclasstyps = 0;

    public static int isclear = -1;

    private String temptitle = "";
    private TextView tv_save;
    public static int CANVAS_WIDTH;
    public static int CANVAS_HEIGHT;
    public static int SCREEN_HEIGHT;
    public static int SCREEN_WIDTH;
    public static int UP_WIDTH;
    public ImageView up ,down;

    @Override
    protected int setView() {
        return R.layout.main;
    }

    @Override
    protected void findViews() {
        mainContainer = (ViewGroup) findViewById(R.id.mainContainer);
        iv_paintStyle = (RadioButton) findViewById(R.id.rb_paintStyle);
        iv_eraser = (RadioButton) findViewById(R.id.rb_eraser);
        tv_finish = (TextView) findViewById(R.id.tv_finish);
        tv_save = (TextView) findViewById(R.id.tv_save);
        iv_exit = (ImageView) findViewById(R.id.iv_exit);
        mPallete = (CWPallete) findViewById(R.id.pallete);
        panel = (CWPanel) findViewById(R.id.panel);
        up=(ImageView)findViewById(R.id.up);
        down=(ImageView)findViewById(R.id.down);

    }

    /**
     * 图片保存地址
     */
    private String mCameraPath;

    @Override
    protected void init() {
        mCameraPath = getIntent().getStringExtra(PHOTOPATH);
        mainContainer.setOnClickListener(this);
        tv_save.setOnClickListener(this);
        up.setOnClickListener(this);
        down.setOnClickListener(this);
//        iv_paintStyle.setOnClickListener(this);
        CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (buttonView.isChecked()) {
                    int id = buttonView.getId();
                    if (id == R.id.rb_paintStyle) {//选中画笔
                        int flag = Integer.parseInt(iv_paintStyle.getTag().toString());
//                        if (flag == PAINT_STYLE_SELECT) {
//                        if (true) {
//                            createPaintStyle();
//                            mPaintStyle.showAsDropDown(iv_paintStyle, (iv_paintStyle.getWidth() - POPU_PAINT_STYLE_WIDTH) / 2, 0);

//                            mPallete.setColor(Color.BLACK);
//                            mPallete.setWidth(2);
//                        } else {
                        mPallete.setBrush();
                        clearSelectStatus();
                        mPallete.setColor(Color.BLACK);
                        mPallete.setWidth(2);
                        iv_paintStyle.setTag(PAINT_STYLE_SELECT);
                    } else if (id == R.id.rb_eraser) {//选中橡皮擦
                        clearSelectStatus();
                        mPallete.setEaser();
                        mPallete.setColor(Color.WHITE);
                    }
                }
            }
        };
        iv_paintStyle.setOnCheckedChangeListener(onCheckedChangeListener);
        iv_eraser.setOnCheckedChangeListener(onCheckedChangeListener);
        tv_finish.setOnClickListener(this);
        iv_exit.setOnClickListener(this);
        POPU_PAINT_STYLE_WIDTH = getResources().getInteger(R.integer.popu_paint_style_width);
        iv_paintStyle.setTag(PAINT_STYLE_SELECT);

        final DisplayMetrics outMetrics = getResources().getDisplayMetrics();
        if (outMetrics.widthPixels < outMetrics.heightPixels) {
            SCREEN_HEIGHT = outMetrics.widthPixels;
            SCREEN_WIDTH = outMetrics.heightPixels;
        } else {
            SCREEN_WIDTH = outMetrics.widthPixels;
            SCREEN_HEIGHT = outMetrics.heightPixels;
        }
        CANVAS_WIDTH = SCREEN_WIDTH;
        CANVAS_HEIGHT = SCREEN_HEIGHT;
        UP_WIDTH=0;
        //mPallete.setMinimumHeight(SCREEN_HEIGHT*2*2*2);
        File HandWrittenFile = new File(mCameraPath);
        if (HandWrittenFile.exists()) {
            editImage(mCameraPath);
        } else {
            addJournal();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_CAPTURE:
                    break;
                case REQUEST_CODE_MEDIA:
                    break;
                case REQUEST_CODE_PERMISSION_SET:
                    break;
                case REQUEST_CODE_PERMISSION_MODIFY:
                    break;
            }
        } else {
            switch (requestCode) {
                case REQUEST_CODE_LOGIN:
                    break;
            }
        }
    }

    /**
     * 删除日志后的操作 设置title,清空画板,清空状态，清空日志分类
     * TODO method comment。
     */
    public void DelImges() {
        mPallete.clearScreen();
        mPallete.isWrite();
        mPallete.clearWrite();
    }

    /**
     * 显示日志
     *
     * @param //JournalContent 日志内容
     */
    public void showContent() {
        isWrite = false;
        mPallete.clearWrite();
        // panel.setPager(mJournalContent.getPagerType());

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_save) {
            SaveImage();
        } else if (v.getId() == R.id.rb_paintStyle) {
//            int flag = Integer.parseInt(iv_paintStyle.getTag().toString());
//            if (flag == PAINT_STYLE_SELECT) {
//                createPaintStyle();
//                mPaintStyle.showAsDropDown(iv_paintStyle, (iv_paintStyle.getWidth() - POPU_PAINT_STYLE_WIDTH) / 2, 0);
//            } else {
//                mPallete.setBrush();
//                clearSelectStatus();
//                iv_paintStyle.setTag(PAINT_STYLE_SELECT);
//            }
        } else if (v.getId() == R.id.rb_eraser) {
//            clearSelectStatus();
//            mPallete.setEaser();
        } else if (v.getId() == R.id.tv_finish) {
            SaveImage();
            finish();
        } else if (id == R.id.iv_exit) {
            finish();
        }
        else if(v.getId()==R.id.down){
            int w=View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
            int h=View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
            mPallete.measure(w,h);
            int  height=mPallete.getMeasuredHeight();
            if(UP_WIDTH<SCREEN_HEIGHT*3&&UP_WIDTH<(height-SCREEN_HEIGHT)){
                UP_WIDTH+=200;
                //controlKeyboardLayout(mPallete,UP_WIDTH);
                //mPallete.scrollto(UP_WIDTH);
                mPallete.scrollTo(0,UP_WIDTH);
            }
            mPallete.invalit();
        }else if(v.getId()==R.id.up){
            if(UP_WIDTH>0){
                UP_WIDTH-=200;
                mPallete.scrollTo(0,UP_WIDTH);
            }
            mPallete.invalit();
        }
    }

    /**
     * 将本次操作的所有List,取出拼接成String
     *
     * @param paths 查询出的list集合
     * @return
     */
    public String getPaths(List<Map> paths) {
        String path = "";
        if (paths != null) {
            if (paths.size() > 0) {
                // 2.获取数据库已存在的数据
                for (int i = 0; i < paths.size(); i++) {
                    path += paths.get(i).get("imgae_path") + ",";
                }
            }
        }
        return path;
    }

    /**
     * 图片是否存在SD卡
     * TODO method comment。
     *
     * @param tmImages //图片地址
     * @return
     */
    public boolean isExistImage(String tmImages) {
        File file = new File(tmImages);
        return file.isFile();
    }

    /**
     * 更新图片
     *
     * @param filename 图片名称
     * @return
     */
    public boolean UpdateImage(String filename) {
        Bitmap mBitmaps = mPallete.getBitmap();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filename);
            mBitmaps.compress(CompressFormat.PNG, 80, out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        isWrite = false;
        mPallete.clearWrite();
        return true;
    }

    /**
     * 保存图片的方法，以判断未对当前页操作时，不做添加处理 TODO method comment。
     *
     * @param //one_pages 当前页
     * @param //sum_pages 总页数
     */
    public boolean SaveImage() {
//        mJournalContent.setCreateTime(System.currentTimeMillis());
        Bitmap mBitmaps = mPallete.getBitmap();
        if (mBitmaps != null) {
//            String lastPath = (BaseSystem.getImagesPath() + "/" + mJournalContent.getCreateTime()) + ".png";
            String lastPath = mCameraPath;
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(lastPath);
                mBitmaps.compress(CompressFormat.PNG, 80, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
                maps = new HashMap<String, Object>();
//              maps.put("index", mJournalContent.getCreateTime());
                maps.put("imgae_path", lastPath);
                maps.put("isWrite", mPallete.isWrite());
                oldlist.add(maps);
                tempPath = lastPath;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        setResult(RESULT_OK);
        CWToast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        return true;
    }

    /**
     * 添加一个新的日志
     */
    private void addJournal() {
        mPallete.clearScreen();
        showContent();
    }

    /**
     * TODO method comment。
     *
     * @param bm
     * @return
     */
    public static InputStream Bitmap2IS(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.PNG, 100, baos);
        InputStream sbs = new ByteArrayInputStream(baos.toByteArray());
        return sbs;
    }

    // 缩放图片
    public static Bitmap zoomImg(String img, int newWidth, int newHeight) {
        // 图片源
        Bitmap bm = BitmapFactory.decodeFile(img);
        if (null != bm) {
            return zoomImg(bm, newWidth, newHeight);
        }
        return null;
    }

    public static Bitmap zoomImg(Context context, String img, int newWidth,
                                 int newHeight) {
        // 图片源
        try {
            Bitmap bm = BitmapFactory.decodeStream(context.getAssets()
                    .open(img));
            if (null != bm) {
                return zoomImg(bm, newWidth, newHeight);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    // 缩放图片
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                true);
        return newbm;
    }

    /**
     * 清楚操作
     */
    private void delete() {
        mPallete.clearWrite();
        mPallete.clearScreen();
        clearSelectStatus();
        iv_paintStyle.setTag(PAINT_STYLE_SELECT);
    }

    /**
     * 清楚所有状态
     */
    private void clearSelectStatus() {
        iv_paintStyle.setTag(PAINT_STYLE_NORMAL);
    }

    /**
     * 颜色笔
     */
    private void createPaintStyle() {
        if (mPaintStyle == null) {
            final ViewGroup view = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.paint_style, null);
            mPaintStyle = new PopupWindow(view, BaseSystem.getPxByDpi(JournalActivity.this, 280), LayoutParams.WRAP_CONTENT, true);
            final int len = view.getChildCount();
            final List<Circle> circles = new ArrayList<Circle>();
            final List<Square> squars = new ArrayList<Square>();
            for (int i = 0; i < len; i++) {
                final ViewGroup container = (ViewGroup) view.getChildAt(i);
                int l = container.getChildCount();
                for (int j = 0; j < l; j++) {
                    final View btn = container.getChildAt(j);
                    if (btn instanceof Circle) {
                        circles.add((Circle) btn);
                    } else {
                        squars.add((Square) btn);
                    }
                    btn.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (v instanceof Square) {
                                int len = squars.size();
                                for (int i = 0; i < len; i++) {
                                    Square s = squars.get(i);
                                    if (s == v) {
                                        s.setSelected();
                                        mPallete.setColor(s.getColor());
                                    } else {
                                        s.cancelSelected();
                                    }
                                }
                            } else if (v instanceof Circle) {
                                int len = circles.size();
                                for (int i = 0; i < len; i++) {
                                    Circle c = circles.get(i);
                                    if (c == v) {
                                        c.setSelected();
                                        mPallete.setWidth(c.getPaintWidth());
                                    } else {
                                        c.cancelSelected();
                                    }
                                }
                            }
                            mPaintStyle.dismiss();
                        }
                    });
                }
            }
            mPaintStyle.setOutsideTouchable(true);
        }
    }

    //将图片添加到画布当中
    public void editImage(String path) {
        File file = new File(path);
        if (file.exists()) {
            mPallete.setImagePath(path);
        } else {
            CWToast.alert(this, R.string.del_error).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
